package com.example.firstspringboot.controller;

import com.example.firstspringboot.bean.User;
import com.example.firstspringboot.result.Result;
import com.example.firstspringboot.result.ResultCode;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/v2/user")
public class UserController2 {
    private static HashMap<Long, User> users;

    static {
        users = new HashMap<>();
        users.put(1L, new User(1L, "zwz", 20));
    }

    /**
     * <p>GET请求，得到所有 user</p>
     * <p>url(Get): <code>localhost:8080/v2/user/</code></p>
     */
    @GetMapping("/")
    public Result<List<User>> getAllUser() {
        List<User> list = new ArrayList<>(users.values());
        return Result.success(list);
    }

    /**
     * <p>GET请求，根据 id 获得 user</p>
     * <p>url(Get): <code>localhost:8080/v2/user/1</code></p>
     */
    @GetMapping("/{id}")
    public Result getUserById(@PathVariable("id") Long id) {
        if (users.containsKey(id)) {
            return Result.success(users.get(id));
        }
        return Result.fail(ResultCode.ID_NOT_FOUND);
    }

    /**
     * <p>POST请求，添加一个 user</p>
     * <p>url(Post): <code>localhost:8080/v2/user/</code></p>
     * <p>body</p>
     * <pre>
     * {
     *     "id": 1,
     *     "name": "zwz"
     *     "age": "20"
     * }
     * </pre>
     */
    @PostMapping("/")
    public Result addUser(@RequestBody User user) {
        Long id = user.getId();
        if (id == null) {
            return Result.fail(ResultCode.ID_NOT_FOUND);
        }
        if (users.containsKey(id)) {
            return Result.fail(ResultCode.ID_DUPLICATED);
        }
        users.put(id, user);
        return Result.success(user);
    }

    /**
     * <p>PUT请求，用来更新 User 信息（ id 值一般不做修改）</p>
     * <p>url(Put): <code>localhost:8080/v2/user/</code></p>
     */
    @PutMapping("/")
    public Result updateUser(@RequestBody User user) {
        Long id = user.getId();
        if (!users.containsKey(id)) {
            return Result.fail(ResultCode.ID_NOT_FOUND);
        }
        users.put(id, user);
        return Result.success(user);
    }

    /**
     * <p>DELETE请求，用来删除User</p>
     * <p>url(Put): <code>localhost:8080/v2/user/1</code></p>
     */
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable("id") Long id) {
        if (!users.containsKey(id)) {
            return Result.fail(ResultCode.ID_NOT_FOUND);
        }
        User user = users.get(id);
        users.remove(id);
        return Result.success(user);
    }
}
